import { defaultListRequestParams, tableColumnValueTypes } from '@/config';
import { FILTER_FIELDTYPE } from '@/constants';
import { isNullOrUndefined } from '@/utils/checkType';

import type { ProColumns } from '@ant-design/pro-components';
export function createFilterColumns<T>(filterList: Requestor.FilterResponse[]) {
  return filterList.map((filter) => {
    const { title, field, fieldType, defaultValue, selectItems = [] } = filter;
    const options = (selectItems || []).map((item) => ({ label: item.title, value: item.value }));
    const valueType =
      options && options.length ? 'select' : tableColumnValueTypes[fieldType] || 'text';
    const column: ProColumns<T> = {
      title,
      valueType,
      ellipsis: true,
      hideInTable: true,
      dataIndex: field,
      fieldProps: { defaultValue, options },
    };
    return column;
  });
}
export function createTableRequestParams(
  params: Requestor.TableParams,
  filterList: Requestor.FilterResponse[],
) {
  const { page, limit, ...rest } = defaultListRequestParams;
  const { current = page, pageSize = limit, ...restParams } = params;

  const filters: Requestor.ListFilter[] = filterList
    .filter((filter) => !isNullOrUndefined(restParams[filter.field]))
    .map((filter) => {
      const { field, operator, relation, fieldType, defaultValue } = filter;
      let value = !isNullOrUndefined(restParams[field]) ? restParams[field] : defaultValue;
      if (fieldType === FILTER_FIELDTYPE.DATETIME) {
        value = value.join(' ~ ');
      }
      return { field, operator, relation, fieldType, value };
    });

  const requestParams: Requestor.ListRequestParams = {
    ...rest,
    filters,
    page: current - 1,
    limit: pageSize,
  };
  return requestParams;
}
export default {
  createFilterColumns,
  createTableRequestParams,
};
